package com.heihei.itextdemo.service.impl;

import com.heihei.itextdemo.bo.print.ReportPDFBO;
import com.heihei.itextdemo.bo.print.ReportPDFReq;
import com.heihei.itextdemo.entity.ClassEntity;
import com.heihei.itextdemo.entity.HumanEntity;
import com.heihei.itextdemo.entity.MajorEntity;
import com.heihei.itextdemo.service.DownPdfService;
import com.heihei.itextdemo.service.MajorService;
import com.heihei.itextdemo.util.NumTransUtil;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


@Service
public class DownPdfServiceImpl implements DownPdfService {
    @Resource
    private MajorService majorService;

    @Override
    public void downPdfReport(HttpServletResponse response, ReportPDFReq req) throws IOException, DocumentException {
        dealPdf(response, req);
    }

    private void dealPdf(HttpServletResponse response, ReportPDFReq req) throws DocumentException, IOException {

        List<ReportPDFBO> dataList = req.getSaleList();
        ReportPDFBO pdfbo = dataList.get(0);

        //设置文件名、响应头
        SimpleDateFormat sdf = new SimpleDateFormat("_yyyyMMdd_HHmmss");
        String fileName = "打印确认单" + sdf.format(new Date());
        response.setContentType("application/x-download");
        response.addHeader("Content-Disposition", "attachment;filename="+new String(fileName.getBytes("utf-8"), "ISO8859-1" )+".pdf");

        //Create Document Instance
        Document document = new Document(PageSize.A4);

        //加载字体
        File file = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX+"res/stsong.ttf");
        BaseFont bfChinese = BaseFont.createFont(file.getAbsolutePath(), BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

        //字体
        Font titleFont = new Font(bfChinese, 20, Font.BOLD);
        Font keyFont = new Font(bfChinese, 12, Font.BOLD);
        Font textFont = new Font(bfChinese, 12, Font.NORMAL);
        Font firstTitleFont = new Font(bfChinese, 18, Font.BOLD);
        Font secondTitleFont = new Font(bfChinese, 12, Font.BOLD);
        Font textImgFont = new Font(bfChinese, 8, Font.NORMAL);

        //Create Writer associated with document
//        PdfWriter.getInstance(document, response.getOutputStream());

        PdfWriter writer = null;

        try {
            writer = PdfWriter.getInstance(document, new BufferedOutputStream(new FileOutputStream(new File("C:/Rey/Career/paperless/test.pdf"))));
        } catch (FileNotFoundException | DocumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        document.open();
        document.newPage();

        //加载标题、日期
        addTitleAndDateInfo(document, pdfbo, titleFont, keyFont);



        //添加统计表格信息
//        addStuStatTable(document, dataList, keyFont, textFont);

        //增加下边的详情
//        addDetailTable(document, dataList, textImgFont, firstTitleFont, secondTitleFont);

        //关闭流
        document.close();
    }


    /**
     * 方法描述: 添加大标题和日期
     */
    private void addTitleAndDateInfo(Document document, ReportPDFBO pdfbo, Font titleFont, Font keyFont) throws DocumentException {
        //列数为1的表格
        PdfPTable t = new PdfPTable(2);
        t.setWidthPercentage(100F);  //设置表格宽度 100%
        //大标题，用titleFont字体：20号字加粗
        PdfPCell c1 = new PdfPCell(new Paragraph(pdfbo.getNbr(), keyFont));
        c1.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中
        c1.setBorder(PdfPCell.NO_BORDER);  //不要边框
        t.addCell(c1);

        //再加一格，设置高度，上下间距
//        c1 = new PdfPCell(); c1.setBorder(PdfPCell.NO_BORDER); c1.setFixedHeight(10); t.addCell(c1);

        //再加一格，设置高度，上下间距
//        c1 = new PdfPCell(); c1.setBorder(PdfPCell.NO_BORDER); c1.setFixedHeight(10); t.addCell(c1);
        //日期   使用字体 keyFont ：12号字加粗 2021-02-06 21:40:27
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        c1 = new PdfPCell(new Paragraph(sdf.format(new java.util.Date()), keyFont));
        c1.setHorizontalAlignment(Element.ALIGN_RIGHT);  //水平靠右
        c1.setBorder(PdfPCell.NO_BORDER);  //不要边框
        t.addCell(c1);
        document.add(t);   //把表格t添加进document中
    }

    /**
     * 方法描述: 统计数据表格
     *
     * @param document 文档
     * @param dataList 查询出来的数据
     * @param keyFont 表头字体格式
     * @param textFont 正文字体格式
     * @throws
     * @author duanhengfei
     */
    private void addStuStatTable(Document document, List<MajorEntity> dataList, Font keyFont, Font textFont) throws DocumentException {
        //专业、班级、学生人数统计表
        PdfPTable stuStatTable = new PdfPTable(5);
        float[] widths = {1.5f, 1.5f, 1f, 1f, 1f};
        stuStatTable.setWidths(widths);
        stuStatTable.setWidthPercentage(70F);

        //加一行空行，设置高度，让标题和日期之间有点儿上下间距
        PdfPCell blankCell = new PdfPCell(); blankCell.setBorder(PdfPCell.NO_BORDER); blankCell.setFixedHeight(15); blankCell.setColspan(5); stuStatTable.addCell(blankCell);
        //设置表头
        PdfPCell c2Title = new PdfPCell(new Paragraph("学院", keyFont)); c2Title.setHorizontalAlignment(Element.ALIGN_CENTER); stuStatTable.addCell(c2Title);
        c2Title = new PdfPCell(new Paragraph("班级", keyFont)); c2Title.setHorizontalAlignment(Element.ALIGN_CENTER); stuStatTable.addCell(c2Title);
        c2Title = new PdfPCell(new Paragraph("人数", keyFont)); c2Title.setHorizontalAlignment(Element.ALIGN_CENTER); stuStatTable.addCell(c2Title);
        c2Title = new PdfPCell(new Paragraph("合计", keyFont)); c2Title.setHorizontalAlignment(Element.ALIGN_CENTER); stuStatTable.addCell(c2Title);
        c2Title = new PdfPCell(new Paragraph("总计", keyFont)); c2Title.setHorizontalAlignment(Element.ALIGN_CENTER); stuStatTable.addCell(c2Title);
        //学生总数
        int humanTotalCount = 0;
        int classTotalCount = 0;
        for (MajorEntity major : dataList) {
            humanTotalCount += major.getHumanCount();
            classTotalCount += major.getClassList().size();
        }
        //设置表内容
        for (int i = 0; i < dataList.size(); i++) {
            MajorEntity major = dataList.get(i);
            //专业名称
            PdfPCell c2 = new PdfPCell(new Paragraph(major.getName(), textFont)); c2.setHorizontalAlignment(Element.ALIGN_CENTER);  c2.setRowspan(major.getClassList().size()); stuStatTable.addCell(c2);
            for (int j = 0; j < major.getClassList().size(); j++) {
                ClassEntity classEntity = major.getClassList().get(j);
                //班级名
                c2 = new PdfPCell(new Paragraph(classEntity.getName(), textFont)); c2.setHorizontalAlignment(Element.ALIGN_CENTER); stuStatTable.addCell(c2);
                //班级下人数
                c2 = new PdfPCell(new Paragraph(String.valueOf(classEntity.getHumanList().size()), textFont)); c2.setHorizontalAlignment(Element.ALIGN_CENTER); stuStatTable.addCell(c2);
                if(j==0) {
                    //当前专业下的总人数
                    c2 = new PdfPCell(new Paragraph(String.valueOf(major.getHumanCount()), textFont));
                    c2.setRowspan(major.getClassList().size());
                    c2.setHorizontalAlignment(Element.ALIGN_CENTER); 
                    stuStatTable.addCell(c2);
                }
                if(i == 0 && j==0) {
                    //所有专业的总人数
                    c2 = new PdfPCell(new Paragraph(String.valueOf(humanTotalCount), textFont));
                    c2.setRowspan(classTotalCount);
                    c2.setHorizontalAlignment(Element.ALIGN_CENTER); 
                    stuStatTable.addCell(c2);
                }
            }
        }
        //添加统计数据表
        document.add(stuStatTable);
    }

    /**
     * 方法描述:  添加最下方的详情内容
     *
     * @param document 文档
     * @param dataList 数据List集合
     * @param textImgFont 普通正文字体
     * @param firstTitleFont 一级标题字体
     * @param secondTitleFont 二级标题字体
     * @throws
     * @author duanhengfei
     * @date 2020年12月03日 13:53:16
     */
    private void addDetailTable(Document document, List<MajorEntity> dataList, Font textImgFont, Font firstTitleFont, Font secondTitleFont) throws DocumentException, FileNotFoundException {
        //此处开始，添加下面的图片详情列表
        PdfPTable detailTable = new PdfPTable(4);
        float[] alarmDetailWidths = {1f, 1f, 1f, 1f};
        detailTable.setWidths(alarmDetailWidths);
        detailTable.setWidthPercentage(100F);
        //当前格式化时间
        SimpleDateFormat sdf02 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (int i = 0; i < dataList.size(); i++) {
            MajorEntity major = dataList.get(i);
            //加一行空行，设置高度，跟上边分开些间隔
            PdfPCell cell = new PdfPCell(); cell.setBorder(PdfPCell.NO_BORDER); cell.setFixedHeight(20); cell.setColspan(4); detailTable.addCell(cell);
            //一级大标题
            String firstTitle = NumTransUtil.cvt(i+1) + "、" + major.getName() + "（共" + major.getHumanCount() + "人）";
            cell = new PdfPCell(new Paragraph(firstTitle, firstTitleFont));
            cell.setColspan(4);
            cell.setBorder(PdfPCell.NO_BORDER);
            detailTable.addCell(cell);
            //本地图片存放位置
            File imgDir = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "itext-imgs");
            for (int j = 0; j < major.getClassList().size(); j++) {
                ClassEntity classEntity = major.getClassList().get(j);
                //先加一行空行，跟上面做分隔
                cell = new PdfPCell(); cell.setBorder(PdfPCell.NO_BORDER); cell.setFixedHeight(10); cell.setColspan(4); detailTable.addCell(cell);
                //二级标题
                String secondTitle = (j+1) + ". " + classEntity.getName() + "（共" + classEntity.getHumanList().size() + "人）";
                cell = new PdfPCell(new Paragraph(secondTitle, secondTitleFont));
                cell.setColspan(4);
                cell.setBorder(PdfPCell.NO_BORDER);
                detailTable.addCell(cell);
                //再加一行空行，跟下面的内容做分隔
                cell = new PdfPCell(); cell.setBorder(PdfPCell.NO_BORDER); cell.setFixedHeight(10); cell.setColspan(4); detailTable.addCell(cell);
                for (int k = 0; k < classEntity.getHumanList().size(); k++) {
                    HumanEntity humanEntity = classEntity.getHumanList().get(k);
                    //图片
                    try{
                        Image img = Image.getInstance(getImg(humanEntity, imgDir, 2));
                        img.setBorderWidth(3);
                        img.setBorderColor(new BaseColor(153, 102, 255));
                        cell = new PdfPCell(img);
                        cell.setBorder(PdfPCell.NO_BORDER);
                    }catch (Exception e) {
                        //如果图片解析失败，则留空
                        System.out.println("图片解析失败");
                        cell = new PdfPCell();
                    }
                    cell.setFixedHeight(80F); cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                    cell.setPaddingTop(5); cell.setPaddingBottom(5);
                    detailTable.addCell(cell);
                    //文字描述
                    String content = "姓名：" + humanEntity.getName() + "\n"
                            + "性别：" + getGenderStr(humanEntity.getGender()) + "\n"
                            + "所属专业：" + major.getName() + "\n"
                            + "所属班级：" + classEntity.getName() + "\n"
                            + "注册时间：" + sdf02.format(humanEntity.getCreateTime());
                    cell = new PdfPCell(new Paragraph(content, textImgFont));
                    cell.setBorder(PdfPCell.NO_BORDER); cell.setFixedHeight(80F);
                    cell.setPaddingLeft(7); cell.setPaddingTop(7); cell.setPaddingBottom(5);
                    detailTable.addCell(cell);
                }
                if(classEntity.getHumanList().size() % 2 == 1) {
                    cell = new PdfPCell(); cell.setBorder(PdfPCell.NO_BORDER);
                    detailTable.addCell(cell);
                    detailTable.addCell(cell);
                }
            }
        }
        //添加详情列表
        document.add(detailTable);
    }

    /**
     * 获取图片img
     * @param flag 1 url形式   2本地存储形式
     * @return
     */
    public Image getImg(HumanEntity humanEntity, File imgDir, Integer flag) throws IOException, BadElementException {
        if(flag == 1) {
            Image img = Image.getInstance(new URL(humanEntity.getProfileImg()));
            return img;
        }
        if(flag == 2) {
            Image img = Image.getInstance(new File(imgDir, humanEntity.getLocalImgPath()).getAbsolutePath());
            return img;
        }
        return null;
    }

    /**
     * 获取性别的字符串格式
     * @param gender
     * @return
     */
    private String getGenderStr(Integer gender) {
        if(gender == 1) {
            return "男";
        } else if(gender == 2) {
            return "女";
        } else if(gender == 3) {
            return "妖";
        } else {
            return "未知";
        }
    }
}